
const requireIndirect = typeof __webpack_require__ !== 'undefined' ? __webpack_require__ : require;

interface NodeModule extends NodeJS.Module, ModuleHot { }
declare var module: NodeModule;
interface ModuleHot extends __WebpackModuleApi.Module
{
    i: string;
    parents: string[];
}

const makeHotExport = function (sourceModule: NodeModule): any
{
    const updateModule = () =>
    {
        setTimeout(() =>//避免马上响应导致的错误
        {
            try
            {
                let modules = requireIndirect(sourceModule.id);
                for (let m in modules)
                    new modules[m];
            }
            catch (e)
            {
                console.error(e);
            }
        });
    };

    if (sourceModule.hot)
    {
        // Mark as self-accepted for Webpack (callback is an Error Handler)
        // Update instances for Parcel (callback is an Accept Handler)
        sourceModule.hot.accept(() =>
        {
            console.log(sourceModule.id);
        });
        // Webpack way
        if (sourceModule.hot.addStatusHandler)
        {
            if (sourceModule.hot.status() === 'idle')
            {
                sourceModule.hot.addStatusHandler(status =>
                {
                    if (status === 'apply')
                        updateModule();
                });
            }
        }
    }
};

export function HotCMD(m)
{
    if (module.hot)
    {
        let cache = require.cache;
        // access parent
        let parent = cache[module.parents[0]] as NodeModule;
        if (!parent) return m;
        // remove itself from a cache
        delete cache[module.id];
        return makeHotExport(Object.assign({ id: parent.i }, parent));
    }
    return m;
};
